<?php

namespace app\http\middleware;

use app\models\{Business as model, OperLog,};

use think\Db;

class Business
{
    public function handle($request, \Closure $next)
    {
        $id = session('business_id');
        $business = (new model())->where('id', $id)->find();
        $url = $request->baseUrl();
        if (!$business && $url != '/index/login') {
            return redirect('index/login');
        }
        $request->business = $business;
        if ($request->isPost() && !empty($business['id'])) {
            $menu = config('bmenu.menu')[strtolower($request->controller())] ?? [];
            $topname = $menu['name'] ?? '';
            $sonname = $menu['sub'][strtolower($request->action())]['name'] ?? '';
            $oper = [
                'type' => 3,
                'adminid' => $business['id'],
                'topmenu' => $topname,
                'sonmenu' => $sonname,
                'remark' => $request->post()['id'] ?? 0,
                'data' => json_encode($request->post() ?? [], true)
            ];
            if (!empty($oper['topmenu'])) {
                (new OperLog())->allowfield(true)->save($oper);
            }
        }
        return $next($request);
    }
}
